//
//  ZRetrievePasswordViewController.m
//  shopSN
//
//  Created by yisu on 16/6/13.
//  Copyright © 2016年 yisu. All rights reserved.
//

#import "ZRetrievePasswordViewController.h"
#import "ZYSLoginViewController.h"
@interface ZRetrievePasswordViewController ()<UITextFieldDelegate>

/** 获取验证码按钮 */
@property (nonatomic, strong) UIButton *codeBtn;
/** 验证码TF */
@property (nonatomic, strong) UITextField *codeTF;
/** 密码TF */
@property (nonatomic, strong) UITextField *passwordTF;

/** 获取的手机验证码 Str */
@property(nonatomic,copy)NSString *code;
/** 倒计时 */
@property(nonatomic,strong)NSTimer *timer;
/** 计时时间 */
@property(nonatomic,assign)NSInteger time;

@end

@implementation ZRetrievePasswordViewController

#pragma mark - 隐藏标签栏
- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = HEXCOLOR(0xf0f0f0);
    
    self.title = @"找回密码";
    
    [self initView];//初始化视图
    
}

#pragma mark - ===== 视图初始化 =====
//初始化视图
- (void)initView {
    
    //1 label
    UILabel *messageLb = [[UILabel alloc] initWithFrame:CGRectMake(25, 64+8, __kWidth-50, 40)];
    //messageLb.backgroundColor = __TestOColor;
    //messageLb.text = @"点击获取验证码。系统会给您账号所绑定或注册的手机号 151****0204 发送一条验证短信";
    
    messageLb.textColor = HEXCOLOR(0x939393);
    messageLb.font = MFont(12);
    messageLb.textAlignment = NSTextAlignmentCenter;
    messageLb.numberOfLines = 0;
    [self.view addSubview:messageLb];
    
    //获取手机信息 填入提示信息
    NSString *totalText;
    if (IsNilString(self.phoneStr)) {
        
    }else{
        NSString *insertStr = [NSString stringWithFormat:@"%@****%@",[self.phoneStr substringToIndex:3],[self.phoneStr substringWithRange:NSMakeRange(7,4)]];
        totalText = [NSString stringWithFormat:@"点击获取验证码。系统会给您账号所绑定或注册的手机号 %@ 发送一条验证短信",insertStr];
    }
    messageLb.text = totalText;
    [self setLabeltextAttributes:messageLb];
    
    //2 mainView (图片 文本框 底线 忘记密码按钮)
    UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 64+56, __kWidth, 88)];
    mainView.backgroundColor = HEXCOLOR(0xffffff);
    [self.view addSubview:mainView];
    
    for (int i=0; i<2; i++) {
        //
        UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(15, 44*i, __kWidth-30, 44)];
        [mainView addSubview:subView];
        
        //图片
        UIImageView *titleIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 12, 20, 20)];
        [subView addSubview:titleIV];
        //titleIV.backgroundColor = [UIColor orangeColor];//等待切图
        titleIV.contentMode = UIViewContentModeScaleAspectFit;
        titleIV.image = i?MImage(@"mima.png"):MImage(@"dx.png");
        
        
        
        //文本框
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectZero];
        textField.font = MFont(14);
        textField.textColor = HEXCOLOR(0x333333);
        textField.delegate = self;
        [subView addSubview:textField];
        
        if (i == 0) {
            //忘记密码 按钮
            _codeBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectW(subView)-100, 8, 98, 28)]; //添加余量6
            _codeBtn.layer.borderWidth = 1;
            _codeBtn.layer.borderColor = __DefaultColor.CGColor;
            _codeBtn.layer.cornerRadius = 13;
            _codeBtn.titleLabel.font = MFont(12);
            [_codeBtn setTitle:@"获取验证码" forState:BtnNormal];
            [_codeBtn setTitleColor:__DefaultColor forState:BtnNormal];
            [_codeBtn addTarget:self action:@selector(getCodeAction) forControlEvents:BtnTouchUpInside];
            [subView addSubview:_codeBtn];
            
            //输入密码 文本框
            textField.frame = CGRectMake(CGRectXW(titleIV)+10, 0, CGRectX(_codeBtn)-CGRectXW(titleIV)-20, 44);
            _codeTF = textField;
            _codeTF.placeholder = @"请输入短信验证码";
            //_passwordTF.backgroundColor = __TestGColor;
        }else {
            textField.frame = CGRectMake(CGRectXW(titleIV)+10, 0, CGRectW(subView)-CGRectXW(titleIV)-10, 44);
            _passwordTF = textField;
            _passwordTF.placeholder = @"请设置新密码(6-16个字符)";
            //_phoneTF.backgroundColor = __TestOColor;
        }
        
    }
    
    //3 中间line
    UIImageView *lineIV = [[UIImageView alloc] initWithFrame:CGRectMake(48, 44, __kWidth-48, 1)];
    lineIV.backgroundColor = HEXCOLOR(0xd8d8d8);
    [mainView addSubview:lineIV];
    
    //4 确定按钮
    UIButton *retrievePwdBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, CGRectYH(mainView)+15, __kWidth-30, 44)];
    retrievePwdBtn.backgroundColor = __DefaultColor;
    retrievePwdBtn.titleLabel.font = MFont(16);
    retrievePwdBtn.layer.cornerRadius = 5;
    [retrievePwdBtn setTitle:@"重置密码" forState:BtnNormal];
    [retrievePwdBtn setTitleColor:HEXCOLOR(0xffffff) forState:BtnNormal];
    [retrievePwdBtn addTarget:self action:@selector(retrievePwdBtnAction) forControlEvents:BtnTouchUpInside];
    [self.view addSubview:retrievePwdBtn];
    
}

//设置Label文字指定位置大小 颜色
- (void)setLabeltextAttributes:(UILabel *)label {
    NSString *text = label.text;
    NSUInteger length = [text length];
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:text];
    
    //电话号码 字符颜色
    [attri addAttribute:NSForegroundColorAttributeName value:HEXCOLOR(0x333333) range:NSMakeRange(length-20, 11)];
    [label setAttributedText:attri];
    
}






#pragma mark - ===== 按钮方法 =====
//获取验证码
- (void)getCodeAction {
    NSLog(@"获取验证码");
    
    [ZHttpRequestService POST:@"Login/sendCode" withParameters:@{@"mobile":self.phoneStr}  success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            NSArray *data=jsonDic[@"data"];
            if (data.count) {
                NSDictionary *dic=data[0];
                _code = dic[@"sms_code"];
                
            }
            [SXLoadingView showAlertHUD:@"获取成功，注意查收" duration:SXLoadingTime];
            
        }else{
            [SXLoadingView showAlertHUD:@"获取验证码失败" duration:SXLoadingTime];
        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:@"获取验证码失败" duration:SXLoadingTime];
    } animated:NO withView:nil];
    
 
    
    if (_timer) {
        [_timer invalidate];
    }
    _codeBtn.userInteractionEnabled=NO;
    _time=60;
    [_codeBtn setTitle:@"60秒后重新获取" forState:BtnNormal];
    _timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(reduceTime:) userInfo:nil repeats:YES];
    
    
}

-(void)reduceTime:(NSTimer*)sender{
    _time--;
    if (_time<=0) {
        [sender invalidate];
        _codeBtn.userInteractionEnabled=YES;
        [_codeBtn setTitle:@"获取验证码" forState:BtnNormal];
    }else{
        NSString *btnTilte=[NSString stringWithFormat:@"%d秒后重新获取",_time];
        [_codeBtn setTitle:btnTilte forState:BtnNormal];
    }
}




- (void)retrievePwdBtnAction {
    
    //判断输入内容是否正确
    [self checkTextFieldContent];
    
    
    
    
}

//判断输入内容是否正确
- (void)checkTextFieldContent {
    
    //NSLog(@"对比结果===%@===%@",_codeTF.text, _code);
    
    //1 code
    if (!IsEquallString(_codeTF.text, _code)) {
        [SXLoadingView showAlertHUD:@"验证码不正确" duration:SXLoadingTime];
        return;
    }
    
    
    //2 password
    if (IsNilString(_passwordTF.text)) {
        [SXLoadingView showAlertHUD:@"密码不可为空" duration:SXLoadingTime];
        return;
    }
    if (_passwordTF.text.length < 6 || _passwordTF.text.length > 16 ) {
        [SXLoadingView showAlertHUD:@"输入密码不正确" duration:SXLoadingTime];
        return;
    }
    
    
    

    //重置密码请求
    [self resetPasswordRequest];
    
}





//重置密码请求
- (void)resetPasswordRequest {
    
    // 115.159.146.202/api/api.php?action=rest_password&mobile=18808051113&password=123455
    NSDictionary *params =@{@"mobile":_phoneStr,
                            @"sms_code":_codeTF.text,
                            @"password":_passwordTF.text,
                            };
    
    [ZHttpRequestService POST:@"Login/reset" withParameters:params success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            
            
            [SXLoadingView showAlertHUD:@"重置密码成功" duration:SXLoadingTime];
            [self returnLoginPage];//返回登录页面
            
        }else{
            NSString *message = jsonDic[@"message"];
            
            [SXLoadingView showAlertHUD:message duration:2];
        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:@"重置密码失败" duration:SXLoadingTime];
        //NSLog(@"%@",error);
    } animated:NO withView:nil];
    
    
    
    
//    NSString *path = [TestRootURL stringByAppendingString:@"/api.php?action=rest_password"];
////    NSDictionary *params =@{@"mobile":_phoneStr,
////                            @"sms_code":_codeTF.text,
////                            @"password":_passwordTF.text,
////                            };
//    [ZHttpRequestService POST:path withParameters:params success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
//        if (succe) {
//            
//            
//            [SXLoadingView showAlertHUD:@"重置密码成功" duration:SXLoadingTime];
//            //返回登录页面
//            [self returnLoginPage];
//            
//        }else{
//            NSString *message = jsonDic[@"message"];
//            
//            [SXLoadingView showAlertHUD:message duration:2];
//        }
//    } failure:^(NSError *error) {
//        [SXLoadingView showAlertHUD:@"重置密码失败" duration:SXLoadingTime];
//        //NSLog(@"%@",error);
//    } animated:YES withView:nil];
    
}

//返回登录页面
- (void)returnLoginPage {
    NSLog(@"重置密码成功，返回登录页面");
    ZYSLoginViewController *vc = [[ZYSLoginViewController alloc]init];
    [self.navigationController popToViewController:vc animated:YES];
}

#pragma mark - ===== 移除键盘 =====
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (_passwordTF || _codeTF) {
        [self.view endEditing:YES];
    }
}


#pragma mark -UITextFiledDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - others
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
